// controller/LoginController.java
package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.UserPojo;
import com.lei.springbootpractice.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    // 添加明确的视图解析指令
    @GetMapping("/login")
    public ModelAndView showLoginForm() {
        return new ModelAndView("login"); // 显式指定视图对象
    }


    @PostMapping("/login")
    public String login(@RequestParam String userID,
                        @RequestParam String password,
                        HttpSession session, // 添加会话参数
                        Model model) {
        if (userService.validateLogin(userID, password)) {
            UserPojo user = userService.getUserByUserID(userID);
            session.setAttribute("loggedInUser", userID);
            session.setAttribute("userRole", user.getRole());

            // 根据角色跳转
            return switch (user.getRole()) {
                case "admin" -> "redirect:/admin/dashboard";
                case "courier" -> "redirect:/courier/dashboard";
                default -> "redirect:/customer/dashboard";
            };
        }else {
            model.addAttribute("error", "账号或密码错误");
            return "login";
        }
    }

    @GetMapping("/welcome")
    public String welcome(HttpSession session, Model model) {
        // 从会话中获取用户信息
        String userID = (String) session.getAttribute("loggedInUser");

        // 查询用户详细信息
        UserPojo user = userService.getUserByUserID(userID);

        // 传递数据到模板
        model.addAttribute("username", user.getUserName());
        return "welcome";
    }
}
